from flask import Flask, request, jsonify
import sqlite3
import uuid
from datetime import datetime, timedelta
import hashlib
import hmac

app = Flask(__name__)

# 配置项 - 实际部署时应该从安全的地方加载
SECRET_KEY = "your-secret-key-1234567890!@#$%^&*()"  # 这个密钥应该足够长且复杂

# 初始化数据库
def init_db():
    conn = sqlite3.connect('license.db')
    c = conn.cursor()
    
    c.execute('''CREATE TABLE IF NOT EXISTS licenses
                 (key TEXT PRIMARY KEY, 
                  created_at TIMESTAMP,
                  is_active BOOLEAN)''')
    
    c.execute('''CREATE TABLE IF NOT EXISTS activations
                 (id INTEGER PRIMARY KEY AUTOINCREMENT,
                  license_key TEXT,
                  machine_id TEXT,
                  activated_at TIMESTAMP,
                  expires_at TIMESTAMP,
                  FOREIGN KEY(license_key) REFERENCES licenses(key))''')
    
    conn.commit()
    conn.close()

def generate_license_keys(count):
    keys = []
    conn = sqlite3.connect('license.db')
    c = conn.cursor()
    
    for _ in range(count):
        key = str(uuid.uuid4()).replace('-', '').upper()[:16]
        print(f"秘钥={key}")
        c.execute("INSERT INTO licenses VALUES (?, ?, ?)",
                  (key, datetime.now(), True))
        keys.append(key)
    
    conn.commit()
    conn.close()
    return keys

def generate_license_signature(license_key, machine_id, expires_at):
    message = f"{license_key}{machine_id}{expires_at}".encode('utf-8')
    return hmac.new(SECRET_KEY.encode('utf-8'), message, hashlib.sha256).hexdigest()

@app.route('/api/check_license', methods=['POST'])
def check_license():
    data = request.json
    license_key = data.get('license_key')
    machine_id = data.get('machine_id')
    
    conn = sqlite3.connect('license.db')
    c = conn.cursor()
    
    # 检查卡密是否存在且有效
    c.execute("SELECT * FROM licenses WHERE key=? AND is_active=1", (license_key,))
    license_data = c.fetchone()
    
    if not license_data:
        conn.close()
        return jsonify({'valid': False, 'message': '无效的卡密'})
    
    # 检查激活次数
    c.execute("SELECT COUNT(*) FROM activations WHERE license_key=?", (license_key,))
    activation_count = c.fetchone()[0]
    
    if activation_count >= 4:
        conn.close()
        return jsonify({'valid': False, 'message': '该卡密已达到最大激活次数(4次)'})
    
    # 检查是否已经在该机器上激活过
    c.execute("SELECT * FROM activations WHERE license_key=? AND machine_id=?", 
              (license_key, machine_id))
    existing_activation = c.fetchone()
    
    expires_at = datetime.now() + timedelta(days=30)  # 1个月有效期
    expires_at_str = expires_at.strftime('%Y-%m-%d %H:%M:%S.%f')
    
    if existing_activation:
        # 检查是否过期
        existing_expires = datetime.strptime(existing_activation[4], '%Y-%m-%d %H:%M:%S.%f')
        if datetime.now() < existing_expires:
            signature = generate_license_signature(license_key, machine_id, existing_activation[4])
            conn.close()
            return jsonify({
                'valid': True, 
                'message': '卡密已验证', 
                'activated': True,
                'expires_at': existing_activation[4],
                'signature': signature
            })
        else:
            # 更新过期时间
            c.execute("UPDATE activations SET expires_at=? WHERE license_key=? AND machine_id=?",
                      (expires_at_str, license_key, machine_id))
    else:
        # 添加激活记录
        c.execute("INSERT INTO activations (license_key, machine_id, activated_at, expires_at) VALUES (?, ?, ?, ?)",
                  (license_key, machine_id, datetime.now(), expires_at_str))
    
    # 生成签名
    signature = generate_license_signature(license_key, machine_id, expires_at_str)
    
    conn.commit()
    conn.close()
    return jsonify({
        'valid': True, 
        'message': '卡密激活成功', 
        'activated': True,
        'expires_at': expires_at_str,
        'signature': signature
    })

@app.route('/api/validate_license', methods=['POST'])
def validate_license():
    data = request.json
    license_key = data.get('license_key')
    machine_id = data.get('machine_id')
    client_signature = data.get('signature', '')
    
    conn = sqlite3.connect('license.db')
    c = conn.cursor()
    
    c.execute("SELECT expires_at FROM activations WHERE license_key=? AND machine_id=?", 
              (license_key, machine_id))
    activation = c.fetchone()
    
    if not activation:
        conn.close()
        return jsonify({'valid': False, 'message': '未找到激活记录'})
    
    expires_at = activation[0]
    
    # 验证签名
    server_signature = generate_license_signature(license_key, machine_id, expires_at)
    if server_signature != client_signature:
        conn.close()
        return jsonify({'valid': False, 'message': '签名验证失败'})
    
    # 检查有效期
    expires_date = datetime.strptime(expires_at, '%Y-%m-%d %H:%M:%S.%f')
    valid = datetime.now() < expires_date
    
    conn.close()
    return jsonify({
        'valid': valid,
        'message': '卡密有效' if valid else '卡密已过期',
        'expires_at': expires_at
    })

@app.route('/api/verify_signature', methods=['POST'])
def verify_signature():
    data = request.json
    signature = generate_license_signature(
        data['license_key'],
        data['machine_id'],
        data['expires_at']
    )
    return jsonify({'valid': signature == data['signature']})

if __name__ == '__main__':
    init_db()
    generate_license_keys(10)  # 取消注释生成测试卡密
    app.run(host='0.0.0.0', port=5000, debug=False)